import React, { useState, useEffect, Fragment } from 'react';
import Crumbs from '../../components/crumbs/index';
import { getStoreList, getClassList, deleteItem as delItem } from '../../api/store';
import { Button, Table, Pagination, Select, message } from 'antd';
import './scss/mallList.scss';
const { Option } = Select;

const MallList = (props) => {
  const [MallList, setMallList] = useState([]);
  // 顶部选项卡切换
  const [tabIndex, setTabIndex] = useState(0);
  // 当前页数
  const [tableIndex, setTableIndex] = useState(1);
  // 一页显示多少个
  const [TabNum, setTabNum] = useState(4);
  const [stateList] = useState(['全部商品', '出售中', '已售罄', '仓库中', '回收站']);
  const columns = [
    {
      title: '排序',
      dataIndex: 'index',
      align: 'center',
      render: (index) => <div>{index + 1}</div>,
    },
    {
      title: '商品',
      dataIndex: 'key',
      align: 'center',
      render: (index) => (
        <div className="mallItem flex">
          <img src={searchImgName(index)[0]} alt="image" className="mallKey" />
          <div className="mallItemName">{searchImgName(index)[1]}</div>
        </div>
      ),
    },
    {
      title: '商品类型',
      align: 'center',
      dataIndex: '',
      render: () => <div>积分商品</div>,
    },
    {
      title: '活动类型',
      align: 'center',
      dataIndex: '',
      render: () => <div>兑换</div>,
    },
    {
      title: '消耗',
      align: 'center',
      dataIndex: 'integration',
      render: (text) => <div>-{text}积分</div>,
    },
    {
      title: '兑换人数',
      align: 'center',
      dataIndex: 'inventory',
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'state',
      render: (text) => <div>{stateList[text]}</div>,
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'key',
      render: (key) => (
        <div>
          {tabIndex === 4 ? (
            <Fragment>
              <Button type="link" onClick={() => pushItem(key)}>
                恢复商品
              </Button>
            </Fragment>
          ) : (
            <Fragment>
              <Button type="link" onClick={() => getItem(key)}>
                修改
              </Button>
              <Button type="link" onClick={() => deleteItem(key)}>
                删除
              </Button>
            </Fragment>
          )}
        </div>
      ),
    },
  ];
  useEffect(() => {
    getStoreList().then((res) => {
      if (res.code === 200) {
        sortAllList(res);
      }
    });
    return () => {};
  }, []);
  const [CrumbsList] = useState([
    {
      name: '积分商城',
    },
    {
      name: '商城列表',
      url: '/MallList',
    },
  ]);
  // 顶部选项卡切换
  let updateTab = (index) => {
    setTabIndex(index);
    getClassList({ index }).then((res) => {
      if (res.code === 200) {
        sortAllList(res);
      } else if (res.code === 204) {
        setMallList([]);
      }
    });
  };
  // 分页器点击事件
  let pagChange = (e) => {
    setTableIndex(e);
  };
  // 下拉框change事件
  let selectChange = (e) => {
    setTabNum(e);
  };
  // 根据key值找到图片和名字
  let searchImgName = (key) => {
    let item = MallList.find((item) => item.key === key);
    let img = JSON.parse(item.imageList);
    return [img[0], item.name];
  };

  // 删除指定项
  let deleteItem = (key) => {
    delItem({ key, isdelete: '2', state: '4' }).then((res) => {
      if (res.code === 200) {
        sortAllList(res);
        message.success('删除成功!请在回收站查看');
      } else if (res.code === 204) {
        message.error('失败，请稍后再试!');
      }
    });
  };

  // 恢复指定项
  let pushItem = (key) => {
    delItem({ key, isdelete: '1', state: '1' }).then((res) => {
      if (res.code === 200) {
        sortAllList(res);
        setTabIndex(0);
        message.success('恢复成功');
      } else if (res.code === 204) {
        message.error('失败，请稍后再试!');
      }
    });
  };

  // 排序
  let sortAllList = (res) => {
    let dataList = res.data.reverse();
    let newData = dataList.sort((a, b) => a.sort - b.sort);
    for (let i = 0; i < newData.length; i++) {
      newData[i].index = i;
    }
    setMallList(newData);
  };

  // 添加商品
  let addItem = () => {
    props.history.push('/additem');
  };

  // 修改商品
  let getItem = (id) => {
    let item = MallList.find((item) => item.key === id);
    props.history.push({
      pathname: '/additem',
      state: item,
    });
  };

  return (
    <div className="MallList">
      <Crumbs CrumbsList={CrumbsList} />
      <ul className="MallListTab flex">
        {stateList.map((item, index) => {
          return (
            <li
              key={item + index}
              className={tabIndex === index ? 'liActive' : ''}
              onClick={() => updateTab(index)}>
              {item}
            </li>
          );
        })}
      </ul>
      <Button className="appMallBtn" onClick={addItem}>
        添加商品
      </Button>
      <div className="tableList">
        <Table
          columns={columns}
          dataSource={MallList.slice((tableIndex - 1) * TabNum, tableIndex * TabNum)}
          bordered
          pagination={false}
          className="tableClassMall"
        />
      </div>
      <div className="mallPag">
        <span>共 {MallList.length} 条</span>
        <div className="mallSelect">
          每页
          <Select defaultValue="4" className="selsectClass" onChange={selectChange}>
            <Option value="4">4</Option>
            <Option value="6">6</Option>
            <Option value="8">8</Option>
            <Option value="10">10</Option>
          </Select>
          条
        </div>
        <Pagination
          size="small"
          total={MallList.length}
          showQuickJumper
          current={tableIndex}
          onChange={pagChange}
          pageSize={TabNum}
        />
      </div>
    </div>
  );
};

export default MallList;
